<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./index.css">
</head>
<body>
  <script src="./js/template.js"></script>
  <script src="./js/jquery.js"></script>
  
  <script id="test" type="text/html">
      {{each list as value i}} 
       <!-- 聊天框 -->
      <div class="chat">
        <!-- 左边的人 -->
        {{if value.user_id != 1}}
        <p>
          <div class="chat_left">
            <!-- 头像 -->
            <img class="img" src="./images/left.png" alt="" srcset="">
            <!-- 说话内容 -->
            <div class="content_left">
              <div class="triangle-left"></div>
              <span>{{@ value.title}}</span>
            </div>
          </div>
        </p>
        {{/if}}
        <!-- 右边的人 -->
        {{if value.user_id==1}}
        <p>
          <div class="chat_right">
            <!-- 说话内容 -->
            <div class="content_right">
              <span>{{@ value.title}}</span>
              <div class="triangle-right"></div>
            </div>
            <!-- 头像 -->
            <img class="img" src="./images/right.png" alt="" srcset="">
          </div>
        </p>
        <!-- 用于清除浮动 -->
        <div class="clear"></div>
      </div>
      {{/if}}
      {{/each}}
  </script> 
  <!-- 大框 -->
  <div class="box">
    <div class="chats">
      <div id="content"></div> 
    </div>
    <!-- 输入框 -->
    <div class="input">
      <textarea name="" placeholder="说点什么呗" id="" rows="5"></textarea>
      <p><button id="send">发送</button></p>
    </div>
  </div>
  <script>
    var data = {
      list: [
        {
          user_id: 1,
          title: 'hello'
        },
        {
          user_id: 0,
          title: 'hello'
        }
      ]
    }

    function send (user_id) {
      var user_info = $('textarea').val()
      
      // 判断内容是否为空
      if (user_info == '') {
        alert('请先输入内容')
        return
      }

      // 判断是否有换行符
      var user_info = user_info.replace(/\n/g,"<br/>");
      console.log(user_info)

      // 将数据存储到数组
      data.list.push({user_id: user_id, title: user_info})

      // 清空输入框
      $('textarea').val("")

      // 渲染聊天页面
      var html = template('test', data); 
      document.getElementById('content').innerHTML = html; 

      // 将滚动条显示在最下方
      $('.chats').scrollTop($('.chats').height());
    }

    $('#send').click(function(){
      send(1)
    })
    var html = template('test', data); 
    document.getElementById('content').innerHTML = html; 
  </script>
</body>
</html>